from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import rsa
from datetime import datetime, timedelta

# 生成一个私钥
private_key = rsa.generate_private_key(
    backend=default_backend(),
    public_exponent=65537,
    key_size=2048
)

# 创建一个自签名证书
subject_name = x509.Name([
    # x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, u"example.com")
    x509.NameAttribute(NameOID.COUNTRY_NAME, u"US"),
    x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"California"),
    x509.NameAttribute(NameOID.LOCALITY_NAME, u"San Francisco"),
    x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"My Company"),
    x509.NameAttribute(NameOID.COMMON_NAME, u"mydomain.com"),
])
issuer_name = subject_name

certificate = x509.CertificateBuilder().subject_name(
    subject_name
).issuer_name(
    issuer_name
).public_key(
    private_key.public_key()
).serial_number(
    x509.random_serial_number()
).not_valid_before(
    datetime.utcnow()
).not_valid_after(
    datetime.utcnow() + timedelta(days=10)
).sign(
    private_key=private_key,
    algorithm=hashes.SHA256(),  # 修改这里
    backend=default_backend()
)

# 证书序列化为PEM格式
cert_pem = certificate.public_bytes(serialization.Encoding.PEM)

# 私钥序列化为PEM格式
key_pem = private_key.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.PKCS8,
    encryption_algorithm=serialization.NoEncryption()
)

# 输出证书和私钥
print("私钥:\n", key_pem.decode('utf-8'))
print("证书:\n", cert_pem.decode('utf-8'))